package top.italks.webviewdemo.ui;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Set;
import top.italks.webviewdemo.MainActivity;
import top.italks.webviewdemo.R;
import top.italks.webviewdemo.utils.AndroidtoJs;

public class HtmlCallAndroidActivity extends AppCompatActivity {

    private WebView mWebView;

    @BindView(R.id.progressBar)
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_html_call_android);
        ButterKnife.bind(this);


        mWebView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = mWebView.getSettings();

        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //AndroidtoJS类对象映射到js的test对象
        mWebView.addJavascriptInterface(new AndroidtoJs(this), "android");
        // 先载入JS代码
        // 格式规定为:file:///android_asset/文件名.html
        mWebView.loadUrl("file:///android_asset/htmlCallAndroid.html");

        //方法三
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Uri uri = request.getUrl();
                //识别自定义的协议
                if (uri.getScheme().equals("android")) {
                    if (uri.getAuthority().equals("callandroid")) {

                        //  步骤3：
                        // 执行JS所需要调用的逻辑
                        System.out.println("js调用了Android的方法");
                        // 可以在协议上带有参数并传递到Android上
                        HashMap<String, String> params = new HashMap<>();
                        Set<String> collection = uri.getQueryParameterNames();
                        for (String key : collection) {
                            String value = uri.getQueryParameter(key);
                            Toast.makeText(HtmlCallAndroidActivity.this, value, Toast.LENGTH_SHORT)
                                .show();
                        }
                        //TODO 做网络接口请求

                        //TODO 打开具体的app中某个界面
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        //保证新启动的APP有单独的堆栈，如果希望新启动的APP和原有APP使用同一个堆栈则去掉该项
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        try {
                            startActivityForResult(intent, RESULT_OK);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(HtmlCallAndroidActivity.this, "没有匹配的APP，请下载安装",
                                Toast.LENGTH_SHORT).show();
                        }
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                ///字符串传值
//                String[] str=message.split("&");
//                String[] ageList=str[0].split("=");
//                String age=ageList[1];

                //json传值
                Object obj = new Gson().fromJson(message, Object.class);

                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                JsPromptResult result) {

                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

            //TODO 进度条
            //ProgressBar 组件样式
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                //加载完了之后，要记得隐藏
                if (newProgress == 100) {
                    //gone和invisible区别
                    progressBar.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }
        });

    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        //自定义返回按钮
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }
}
